package com.loop.unclelend.ui.fragment

import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.loop.unclelend.R
import com.loop.unclelend.databinding.UiPageStepAccountBinding
import com.loop.unclelend.pro.ProFragment
import com.loop.unclelend.ui.activity.Act_Steps
import com.loop.unclelend.ui.adapter.Adapter_Step_Account
import com.loop.unclelend.ui.presenter.Pre_Step_Account
import com.loop.unclelend.ui.view.IView_Step_Account
import com.loop.unclelend.utils.dialog.Dialog_BindCard
import com.loop.unclelend.utils.dialog.Dialog_BindCard_Delete
import com.loop.unclelend.utils.dialog.Dialog_BindCard_Other
import com.loop.unclelend.utils.dialog.Dialog_BindCard_Submit
import com.loop.unclelend.utils.dialog.Dialog_BindCard_Submit_Warning
import com.loop.unclelend.utils.event.UncleEventHelper
import com.loop.unclelend.utils.event.UncleEventType
import org.json.JSONObject

/**
 * UncleLend
 * @Author wwdeng
 * @CreateTime: 2024/9/18 10:38
 * @Annotation：认证流程 - 法语地区绑定账户
 */
class Fm_Step_Account(): ProFragment(),IView_Step_Account {
    lateinit var binding: UiPageStepAccountBinding
    var stepItem: JSONObject? = null
    var presenter: Pre_Step_Account? = null

    private var accountAdapter: Adapter_Step_Account? = null

    constructor(stepItem: JSONObject): this(){
        this.stepItem = stepItem
    }

    override fun getUncleRootView(inflater: LayoutInflater): View {
        binding = UiPageStepAccountBinding.inflate(inflater)
        return binding.root
    }

    override fun initUncleView() {
        rootViewBinding.layoutRoot.setBackgroundColor(Color.parseColor("#00000000"))
        binding.txtStepTitle.text = stepItem!!.optString("showTitle")
        initUncleRecyclerViews()
    }

    override fun initUncleListener() {
        //添加
        binding.layoutAdd.setOnClickListener {
            showBinCardAddDialog()
        }

        //提交
        binding.btnNext.setOnClickListener {
            if (!isStepSubmit()){
                showErrorTipsDialog(getString(R.string.tips_submit_error), stepItem!!.optString("stepTitle"))
                return@setOnClickListener
            }
            onCheckSubmitStatus()
        }
    }

    override fun initUncleData() {
        presenter = Pre_Step_Account(this)
        presenter!!.requestAccountListAction()
    }

    /**
     * 初始化Views
     */
    private fun initUncleRecyclerViews(){
        binding.recyclerView.isNestedScrollingEnabled = false
        binding.recyclerView.isFocusableInTouchMode = false //不需要焦点
        val layoutManager = LinearLayoutManager(context)
        layoutManager.orientation = RecyclerView.VERTICAL
        binding.recyclerView.layoutManager = layoutManager
        accountAdapter = Adapter_Step_Account(binding.recyclerView)
        binding.recyclerView.adapter = accountAdapter!!
        binding.recyclerView.itemAnimator = DefaultItemAnimator()
        accountAdapter!!.setOnItemChildClickListener { _, childView, position ->
            val item = accountAdapter!!.getItem(position)
            when(childView.id){
                R.id.layout_edit -> {//添加
                    showBinCardAddDialog()
                }
                R.id.img_delete -> {//删除
                    showDeleteDialog(item)
                }
            }
        }
    }

    /**
     * 已绑定账户列表
     */
    override fun showAccountList(accountList: ArrayList<JSONObject>) {
        accountAdapter!!.data = accountList

        //最多添加10个账户
        if (accountAdapter!!.itemCount >= 10){
            binding.layoutAdd.isEnabled = false
            binding.layoutAdd.visibility = View.GONE
        } else {
            binding.layoutAdd.isEnabled = true
            binding.layoutAdd.visibility = View.VISIBLE
        }
    }

    /**
     * 提示绑定另一个渠道账户
     */
    override fun showBindingAccountOtherDialog(otherInfo: JSONObject) {
        val replaceDialog = Dialog_BindCard_Other(context,stepItem!!.optString("stepTitle"),object : Dialog_BindCard_Other.IDialogCallback{
            override fun onClick(view: View?) {
                if (view!!.id == R.id.btn_confirm){//添加
                    presenter!!.requestBindAccountAction(otherInfo.optString("walletMobile"),otherInfo.optString("value"), "YES")
                }
            }
        })
        replaceDialog.setCancelable(true)
        replaceDialog.setCanceledOnTouchOutside(false)
        replaceDialog.show()
        replaceDialog.setBindAccountInfo(otherInfo)
    }

    /**
     * 添加绑卡dialog
     */
    private fun showBinCardAddDialog(){
        UncleEventHelper.addUncleRequestEventAction(UncleEventType.CLICK.UNCLE_CLICK_USER_ACCOUNT_ADD,stepItem!!.optString("stepTitle"))
        val bindCardDialog = Dialog_BindCard(context,stepItem!!.optString("stepTitle"),object : Dialog_BindCard.IDialogCallback{
            override fun onClick(view: View?) {
            }
            override fun onSubmitParams(typeObj: JSONObject, phoneNumber: String) {
                presenter!!.requestBindAccountAction(phoneNumber,typeObj.optString("value"))
            }
        })
        bindCardDialog.setCancelable(true)
        bindCardDialog.setCanceledOnTouchOutside(false)
        bindCardDialog.show()
    }

    /**
     * 只有一个账户警告提示
     */
    private fun showSubmitWarningDialog(){
        val warningDialog = Dialog_BindCard_Submit_Warning(context,stepItem!!.optString("stepTitle"),object : Dialog_BindCard_Submit_Warning.IDialogCallback{
            override fun onClick(view: View?) {
                when(view!!.id){
                    R.id.btn_no_more -> {//提交(不再有账户)
                        // TODO: 发送通知，更新主流程
                        val act = context as Act_Steps
                        act.showUncleSubmitSuccess()
                    }
                    R.id.btn_add -> {//继续添加
                        showBinCardAddDialog()
                    }
                }
            }
        })
        warningDialog.setCancelable(true)
        warningDialog.setCanceledOnTouchOutside(false)
        warningDialog.show()
    }

    /**
     * 确认dialog
     */
    private fun showConfirmDialog(){
        val submitDialog = Dialog_BindCard_Submit(context,object : Dialog_BindCard_Submit.IDialogCallback{
            override fun onClick(view: View?) {
                if (view!!.id == R.id.btn_confirm){
                    UncleEventHelper.addUncleRequestEventAction(UncleEventType.CLICK.UNCLE_CLICK_USER_ACCOUNT_SUBMIT_TIPS_CONFIRM,"")
                    // TODO: 发送通知，更新主流程
                    val act = context as Act_Steps
                    act.showUncleSubmitSuccess()
                }
            }
        })
        submitDialog.show()
        submitDialog.setBindAccountList(accountAdapter!!.data)
    }

    /**
     * 删除提示
     */
    private fun showDeleteDialog(item: JSONObject){
        UncleEventHelper.addUncleRequestEventAction(UncleEventType.CLICK.UNCLE_CLICK_USER_ACCOUNT_DELETE,item.optString("id"))
        val deleteDialog = Dialog_BindCard_Delete(context,stepItem!!.optString("stepTitle"), object : Dialog_BindCard_Delete.IDialogCallback{
            override fun onClick(view: View?) {
                if (view!!.id == R.id.btn_submit){
                    presenter!!.requestDeleteAccountAction(item.optString("id"))
                }
            }
        })
        deleteDialog.setCancelable(true)
        deleteDialog.setCanceledOnTouchOutside(false)
        deleteDialog.show()
        deleteDialog.setBindAccountInfo(item)
    }

    /**
     * 提交按钮是否可点
     */
    private fun isStepSubmit(): Boolean{
        //提交按钮是否可点
        var submitIsEnabled = false
        for (i in 0..<accountAdapter!!.itemCount){
            //存在一个不是编辑状态的item，则可以提交
            if (!accountAdapter!!.getItem(i).optBoolean("isEdit",true)){
                submitIsEnabled = true
                break
            }
        }
        return submitIsEnabled
    }

    /**
     * 检查提交
     */
    private fun onCheckSubmitStatus(){
        var count = 0
        accountAdapter!!.data.forEach {
            //不是编辑类型
            if (!it.optBoolean("isEdit",true)){
                count += 1
            }
        }
        //只有一个账户，需要提示
        if (count <= 1){
            showSubmitWarningDialog()
            return
        }
        //预览所有账户列表
        showConfirmDialog()
    }

    override fun onStart() {
        super.onStart()
        UncleEventHelper.addUncleRequestEventAction(UncleEventType.PAGE.UNCLE_PAGE_STEP_ACCOUNT_START)
    }

    override fun onDestroy() {
        super.onDestroy()
        UncleEventHelper.addUncleRequestEventAction(UncleEventType.PAGE.UNCLE_PAGE_STEP_ACCOUNT_END)
    }
}